package Utility;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import Context.Context;
import Context.ContextHolder;

/**
 * @category Utility module
 * @author Sean Lionheart
 * @version 1.0.0.0
 * The policy of logging. It creates the log filters.
 */
class LogPolicy {
	
	private ArrayList<ILogFilter> logFilters;		//Contains the log filters.	
	/**
	 * The constructor
	 */
	public LogPolicy() {
		logFilters = new ArrayList<ILogFilter>();
		loadPolicy();
	}
	/**
	 * Get all the filters.
	 * @return all the filters.
	 */
	public ArrayList<ILogFilter> getFilters () {
		return logFilters;
	}
	/**
	 * Load the policy for the configuration.
	 */
	private void loadPolicy() {
		createFilter();
	}
	/**
	 * Make up the filters by the configuration.
	 */
	@SuppressWarnings("unchecked")
	private void createFilter() {
		Context ctx = ContextHolder.getContext();
		Properties allProperties = ctx.getAllProperties();
		
		Iterator it = allProperties.entrySet().iterator();
		while(it.hasNext()) {
			Map.Entry<String,String> entry= (Map.Entry<String,String>) it.next();
			String className = entry.getKey();
			String filterEnable = entry.getValue();
			
			if(className.startsWith(LogContext.LOGFILTER_PREFIX) 
					&& filterEnable.equals(LogContext.ENABLE)) {				
				try {
					Class<ILogFilter> filterClass =  
						(Class<ILogFilter>) Class.forName(className);
					ILogFilter filter = filterClass.newInstance();
					if(filter != null) {
						logFilters.add(filter);
					}
				}
				catch (ClassNotFoundException e) {
					// TODO: handle exception
					e.printStackTrace();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
